# easyrobot hides the class system
# But this will necessity using the global statement to store any extra state...

import sys
from robot import Robot

# Store the instantiated robot here
instantiation = 0

# The sensors dict is overwritten, so this class with reference the current sensors dict
class SensorsDict(dict):
	def __getitem__(self, key):
		return instantiation.sensors[key]

sensors = SensorsDict()

class TheRobot(Robot):
	def __init__(self, name):
		Robot.__init__(self, name)
		
		global instantiation
		instantiation = self
		
		# Look for the initialize and respond functions in imported modules
		for modname, mod in sys.modules.items():
			if mod is not None:
				if 'initialize' in mod.__dict__:
					self.initialize = mod.__dict__['initialize']
				elif 'initialise' in mod.__dict__:
					self.initialize = mod.__dict__['initialise']
				if 'respond' in mod.__dict__:
					self.respond = mod.__dict__['respond']

# The API
def forsteps(steps, f, *p):
	'''for use with the default respond() method.

	This will add an entry to self._steps using the passed
	# of ticks, function, and function parameters.

	'''

	instantiation._steps.append([steps, f, p])

def forseconds(seconds, f, *p):
	'Converts seconds to steps, then calls forsteps()'

	steps = int(seconds*60.0)
	forsteps(steps, f, *p)

def forever(f, *p):
	'''for use with the default respond() method

	Sets a function and parameters to be called non-stop.

	'''

	forsteps(0, f, *p)

def force(n):
	'Between -100 and 100, percent of max fwd/bk force'
	instantiation._force = int(n)

def torque( n):
	'between -100 and 100, percent of max rt/lt torque'
	instantiation._torque = int(n)

def fire(dist=None):
	'''Launch a shell from the cannon.

	If dist is None, the shell will continue until it hits a wall,
	a robot, or another bullet.

	If dist is given, the shell will travel that distance and then
	explode.

	'''

	if dist is None:
		instantiation._fire = 'X'
	else:
		instantiation._fire = int(dist)

def ping():
	'Send out a sonar/radar pulse'
	instantiation._ping = 1

def turret(angle):
	'''Turn the turret to the given angle.

	It takes time for the turret to turn. Check the actual turret
	angle with the TUR sensor:  self.sensors['TUR']

	'''

	instantiation._turretangle = angle

def log(*msgs):
	'Write a message to the log file.'

	if instantiation.logfile is not None:
		msgstrs = map(str, msgs)
		m = ', '.join(msgstrs)
		msg = '%s: %s' % (instantiation.name, m)
		instantiation.logfile.write(msg)
		instantiation.logfile.write('\n')
		instantiation.logfile.flush()


